package fi.solita.dojo.client;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;

public class ClientExample {

	public static void main(String[] args) {

		try {
			InetAddress address = InetAddress.getByName(args[0]);
			Socket socket = new Socket(address, 12111);			
			try {
				clientLoop(socket);
			} finally {socket.close();}
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}	
	}

	public static void clientLoop(Socket socket) throws IOException{
		OutputStreamWriter writer = new OutputStreamWriter(socket.getOutputStream(), "ISO-8859-1");
		BufferedReader stream = new BufferedReader(new InputStreamReader(socket.getInputStream(), "ISO-8859-1"));
		BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
		String line = "";
		try {	
			do {
				System.out.println("-> " + stream.readLine());
				line = console.readLine();
				writer.write(line + "\n");
				writer.flush();
			} while ( !line.equals("quit") );
		} catch (SocketException e) {}
	}
}
